package com.example.netty.ui.model

import android.util.Log
import android.widget.Toast
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.netty.io.client.NettyClient
import com.example.netty.io.core.EventType
import com.example.netty.io.core.NettyLog
import com.example.netty.io.dispatcher.JsonMessageDispatcher
import com.example.netty.io.server.NettyServer
import com.example.netty.pojo.TestPojo
import io.netty.channel.Channel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

private const val TAG = "MainModel"

const val port = 10999

class MainModel : ViewModel() {
    private var isServerRunning = false
    private val nettyServer by lazy {
        NettyServer(port)
    }
    private val nettyClient by lazy {
        NettyClient("0.0.0.0", port, object : JsonMessageDispatcher<TestPojo>() {
            override fun onReceiveJsonObject(pojo: TestPojo?) {
                NettyLog.d(TAG, "onReceiveJsonObject: $pojo")
            }

            override fun onEventArrived(channel: Channel, type: EventType) {
                when (type) {
                    is EventType.DISCONNECTED -> {
                        NettyLog.e(TAG, "onEventArrived: 连接失败")
                    }

                    else -> {

                    }
                }
            }

            override fun getHeartbeat(): ByteArray {
                return "heartbeat from client".toByteArray()
            }
        })
    }

    fun startServer() {
        if (!isServerRunning) {
            isServerRunning = true
            nettyServer.start()
        } else {
            isServerRunning = false
            nettyServer.stop()
        }
    }

    fun startClient() {
        nettyClient.start()
    }

    fun serverSendMessage(message: String) {
        viewModelScope.launch(Dispatchers.IO) {

        }
    }

    fun clientSendMessage(message: String) {
        viewModelScope.launch(Dispatchers.IO) {
            nettyClient.send(message = message)
        }
    }

    fun stopClient() {
        viewModelScope.launch(Dispatchers.IO) {
            nettyClient.stop()
        }
    }
}